package com.shaoshaohuo.app.ui.ec;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.ProductMoreGridviewAdapter;
import com.shaoshaohuo.app.adapter.SpecificationAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.PurchaseDetail;
import com.shaoshaohuo.app.entity.PurchaseDetail.ProductMore;
import com.shaoshaohuo.app.entity.PurchaseDetailEntity;
import com.shaoshaohuo.app.entity.Specification;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.SpecificationDataUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.utils.sharesdk.ShareContent;
import com.shaoshaohuo.app.utils.sharesdk.ShareFactory;
import com.shaoshaohuo.app.view.MeasureGridView;
import com.shaoshaohuo.app.view.TopbarView;

import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform.ShareParams;

/**
 * @ClassName PurchaseDetailActivity
 * @author linmu
 * @Decription 采购详情页 @2015-8-28 下午10:16:42
 */
public class PurchaseDetailActivity extends BaseActivity implements OnClickListener {

    private TopbarView mTopbarView;

    private TextView tv_name;
    private	TextView tv_pinzhong;
    private	TextView tv_price;
    private	TextView tv_unit;
    private	TextView tv_address;
    private	TextView tv_num;
    private	GridView gv_specification;
    private FrameLayout fl_specification;
    private	TextView tv_date;
    private	TextView tv_yaoqiu;
    private	TextView tv_user;

    private ImageView mCallChatImage;
    private ImageView mCallPhoneImage;
    private MeasureGridView mProductGv;
    private Button mNextButton;

    private String id;
    private boolean isSupply = false;

    private PopupWindow hintPopWinwow;

    private PurchaseDetail data;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase_detail);

        initData();
        initView();
        setUpView();
        requestData();
    }

    private void initData() {
        Intent intent = getIntent();
        id = intent.getStringExtra(ExtraName.id);
        isSupply = intent.getBooleanExtra(ExtraName.isSupply, false);
    }

    private void initView() {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_pinzhong = (TextView) findViewById(R.id.tv_pinzhong);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_unit = (TextView) findViewById(R.id.tv_unit);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_num = (TextView) findViewById(R.id.tv_num);
        gv_specification = (GridView) findViewById(R.id.gv_specification);
        fl_specification = (FrameLayout) findViewById(R.id.fl_specification);
        tv_date = (TextView) findViewById(R.id.tv_date);
        tv_yaoqiu = (TextView) findViewById(R.id.tv_yaoqiu);
        tv_user = (TextView) findViewById(R.id.tv_user);

        mCallPhoneImage = (ImageView) this.findViewById(R.id.imageview_call_phone);
        mCallChatImage = (ImageView) this.findViewById(R.id.imageview_call_chat);
        mProductGv = (MeasureGridView) this.findViewById(R.id.gv_service_list);

        mNextButton = (Button) this.findViewById(R.id.button_next);
    }

    private void requestData() {
        startLoadingDialog();
        RequestService.getInstance().getPurchaseDetail(this, id, PurchaseDetailEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    PurchaseDetailEntity entity = (PurchaseDetailEntity) resultData;
                    updataUi(entity);
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }

    protected void updataUi(PurchaseDetailEntity entity) {

        data = entity.getData();

        tv_name.setText(data.getPidname());
        tv_pinzhong.setText(data.getCatname());
        tv_price.setText(data.getNum());
        tv_unit.setText(data.getUnit());
        tv_address.setText(AreaUtil.getAreaFullname(data.getCityid()) + data.getAddress());
        tv_num.setText(data.getNumber());

        if (data.specifications != null && data.specifications.size() > 0) {

            Map<Specification, List<Specification>> specificationMap = SpecificationDataUtil.list2map(data.specifications);
            gv_specification.setAdapter(new SpecificationAdapter(this, gv_specification, specificationMap));
        }else{
            fl_specification.setVisibility(View.GONE);
        }


        tv_date.setText(data.getStart() + "至" + data.getEnd());

        tv_yaoqiu.setText(data.getContent());

        tv_user.setText(data.getRealname());
        
//        if(data.getVarieties().length <=0){
//        	mProductNameText.setText("产品：" + data.getPidname());
//        }else{
//        	mProductNameText.setText("产品：" + getProductName());
//        }
//        mVarietyText.setText(sb.toString());
//        mPurchaseCountText.setText("采购量：" + data.getNum() + data.getUnit());
//        mStandardText.setText("规格：" + data.getProductnot());

//        mBuyerNameText.setText("采购商：" + data.getRealname());
//         mAddressText.setText("收货地址："+data.getAddress());
         
//        mBuyTimeText.setText("收货时间：" + formatBuyTime(data));
//        mRequireText.setText( data.getContent());

        mCallPhoneImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DeviceHelper.callPhone(PurchaseDetailActivity.this, data.getMobile(), data.getKey());
            }
        });
        mCallChatImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            	IMFactory.openChat(PurchaseDetailActivity.this, data.getUserid());
            }
        });
        ProductMoreGridviewAdapter<ProductMore> adapter = new ProductMoreGridviewAdapter<ProductMore>(this, data.getMore(), false);
        mProductGv.setAdapter(adapter);
        
      //禁止联系自己
	 if (AccountManager.getUserId().equals(data.getUserid())) {
		 mCallPhoneImage.setVisibility(View.GONE);
		 mCallChatImage.setVisibility(View.GONE);
	 }
    }
    
    private String getProductName() {
    	StringBuilder sb = new StringBuilder();
      	for (String s : data.getVarieties()) {
      		sb.append(s + " ");
      	}
      	return data.getPidname()+"/"+sb.toString();
    }

    /**
     * 格式化收货时间
     * @param detail
     * @return
     */
    private String formatBuyTime(PurchaseDetail detail) {
    	String start = data.getStart();
    	String end = data.getEnd();
    	String defaultNull = "无";
    	if (defaultNull.equals(start) && defaultNull.equals(end)) {
    		return defaultNull;
    	} else if (defaultNull.equals(start) && !defaultNull.equals(end)) {
    		return "到" + end + "结束";
    	} else if (!defaultNull.equals(start) && defaultNull.equals(end)) {
    		return "从" + start + "开始";
    	} else {
    		return start + "至" + end;
    	}
    	
    }
    


    private void setUpView() {
        mTopbarView.setCenterText("采购详情");
        mTopbarView.setLeftView(true, true);
        mTopbarView.setRightText("分享赚积分");
        mTopbarView.setRightClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
            ShareParams params = new ShareParams();
            params.setTitle(ShareContent.getPurchaseTitle(getProductName(), data.getNum() + data.getUnit()));
            params.setTitleUrl(HttpConfig.WebPage.SHARE_PURCHASE  + "?number=" + data.getNumber());
            params.setUrl(HttpConfig.WebPage.SHARE_PURCHASE + "?number=" + data.getNumber());
            params.setText(ShareContent.getPurchaseText(getProductName(), data.getNum() + data.getUnit(), data.getRealname(), data.getAddress()));
            params.setImageUrl(HttpConfig.WebPage.SHARE_IMAGE_PATH);
            ShareFactory.showShare(PurchaseDetailActivity.this, params);
            }
        });


        if (isSupply) {
            mNextButton.setText("我的报价>>");
        }

        mNextButton.setOnClickListener(this);

    }

    public void shareMsg() {
        if (hintPopWinwow != null && hintPopWinwow.isShowing()) {
            hintPopWinwow.dismiss();
            return;
        }
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View contentView = inflater.inflate(R.layout.view_share_dialog, null, false);
        hintPopWinwow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        hintPopWinwow.setOutsideTouchable(true);
        hintPopWinwow.setBackgroundDrawable(new BitmapDrawable());
        hintPopWinwow.setAnimationStyle(R.style.Anim_Dialog_Bottom);
        View sinaLayout = contentView.findViewById(R.id.layout_share_sina);
        View qqLayout = contentView.findViewById(R.id.layout_share_qq);
        View qqzoneLayout = contentView.findViewById(R.id.layout_share_qqzone);
        View weixinLayout = contentView.findViewById(R.id.layout_share_weixin);
        View pengyouquanLayout = contentView.findViewById(R.id.layout_share_pengyouquan);
        View contactLayout = contentView.findViewById(R.id.layout_share_sms);
        View closeLayout = contentView.findViewById(R.id.textview_close);

        sinaLayout.setOnClickListener(this);
        qqLayout.setOnClickListener(this);
        qqzoneLayout.setOnClickListener(this);
        weixinLayout.setOnClickListener(this);
        pengyouquanLayout.setOnClickListener(this);
        contactLayout.setOnClickListener(this);
        closeLayout.setOnClickListener(this);

        hintPopWinwow.showAtLocation(mTopbarView, Gravity.BOTTOM, 0, 0);
    }

    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button_next:
            if (AccountManager.checkUserAuth(this)) {
                if (isSupply) {
                    Intent intent = new Intent(this, MyQuoteDetailActivity.class);
                    startActivity(intent);
                } else {
                    if(data == null){
                        return;
                    }
                    if(!TextUtils.isEmpty(data.getOrderid())){
                        showToast("您不能给自己报价");
                    }else{
                        Intent intent = new Intent(this, ReleaseQuoteActivity.class);
                        intent.putExtra(ExtraName.id, id);
                        startActivity(intent);
                    }
                }
            }
            return;
        /*case R.id.layout_share_sina:
            AndroidUtils.sendweibo(this, ShareContent.SHARE_TITLE, ShareContent.PURCHASE_CONTENT, HttpConfig.WebPage.SHARE);
            break;
        case R.id.layout_share_qq:
            AndroidUtils.sendqq(this, HttpConfig.WebPage.SHARE, ShareContent.SHARE_TITLE, ShareContent.PURCHASE_CONTENT);
            break;
        case R.id.layout_share_qqzone:
            AndroidUtils.sendkongjian(this, HttpConfig.WebPage.SHARE, ShareContent.SHARE_TITLE, ShareContent.PURCHASE_CONTENT);
            break;
        case R.id.layout_share_weixin:
            AndroidUtils.sendweixin(this, ShareContent.SHARE_TITLE, ShareContent.PURCHASE_CONTENT, HttpConfig.WebPage.SHARE);
            break;
        case R.id.layout_share_pengyouquan:
            AndroidUtils.sendpengyouquan(this, ShareContent.SHARE_TITLE, ShareContent.PURCHASE_CONTENT, HttpConfig.WebPage.SHARE);
            break;
        case R.id.layout_share_sms:
            Uri smsToUri = Uri.parse( "smsto:" );  
            Intent sendIntent =  new  Intent(Intent.ACTION_VIEW, smsToUri);  
            sendIntent.putExtra( "sms_body" ,  ShareContent.PURCHASE_CONTENT+HttpConfig.WebPage.SHARE);  
            sendIntent.setType( "vnd.android-dir/mms-sms" );  
            startActivity(sendIntent);  
            break;*/
        case R.id.textview_close:
            break;
        }

        hintPopWinwow.dismiss();
    }

}
